package chat

import (
	"encoding/json"
	"errors"
	"longmen/server/config/global"
	"longmen/server/pkg/db/mysql"
	"longmen/server/pkg/db/mysql/models/models_main"
	pb "longmen/server/pkg/protobuf"
	"strconv"
	"time"
)

func GetUser(userId int) (*models_main.User, error) {
	exists, err := global.BloomExists(global.BLOOM_ID, strconv.Itoa(userId))
	if err != nil {
		global.Log.Errorf("bloom exists error: %v", err)
	}
	if !exists {
		return &models_main.User{}, nil
	}
	return mysql.GetUserParam(map[string]interface{}{
		"id": userId,
	})

}

func GetClientUser(userId int) *ClientUser {
	user := ClientUser{}
	rds := global.GetRds()
	bytes, err := rds.Get("chat_client_user:" + strconv.Itoa(userId)).Bytes()
	if err != nil {
		return nil
	}
	err = json.Unmarshal(bytes, &user)
	if err != nil {
		return nil
	}
	return &user
}

func SetClientUser(user *ClientUser) *ClientUser {
	rds := global.GetRds()
	marshal, _ := json.Marshal(user)
	status := rds.Set("chat_client_user:"+strconv.Itoa(user.UserId), string(marshal), 10800*time.Second)
	if status.Err() != nil {
		global.Log.Errorf("set client user error: %v", status)
		return nil
	}
	return user
}

func SetClientUserVip(userId int, vip int) {
	clientUser := GetClientUser(userId)
	if clientUser != nil {
		clientUser.Vip = vip
		SetClientUser(clientUser)
	}
}

func SetClientUserName(userId int, name string) {
	clientUser := GetClientUser(userId)
	if clientUser != nil {
		clientUser.ClientName = name
		SetClientUser(clientUser)
	}
}

func GetUserByReq(req *pb.CallbackReq) (*ClientUser, error) {
	var user *ClientUser
	formUserId, _ := strconv.Atoi(req.From_Account)
	user = GetClientUser(formUserId)
	if user == nil || len(user.ClientName) == 0 || user.Role == 0 {
		global.Log.Debugf("NoCache User%v", req)
		return nil, errors.New("用户信息读取出错2")
	}
	return user, nil
}
